import random

from django.shortcuts import render, HttpResponse
import datetime
from blog.models import Powerone, Powerthree, Powertwo, Powerall, Move, Change, Windpressure, Fissure
from django.db.models import Q
from collections import OrderedDict
from django.views.decorators.http import require_http_methods, require_GET
from pyecharts.charts import Line
from pyecharts import options as opts
import numpy
# Create your views here.
app_name="blog"
def index(request):
    result = Powerall.objects.all()
    now_date = datetime.date.today()
    yesterdate = now_date + datetime.timedelta(days=-1)
    chan1 =Fissure.objects.filter(timestamp__contains=now_date)
    chan2 =Fissure.objects.filter(timestamp__contains=yesterdate)
    chan1 = {obj.name: obj for obj in chan1}
    chan2 = {obj.name: obj for obj in chan2}
    ch1 = {}
    ch2 = {}
    for i in chan1.values():
        ch1.update({i.name: i.value})
    for i in chan2.values():
        ch2.update({i.name: i.value})
    changes1 = {k: round(100*(ch1.get(k, 0) - ch2.get(k, 0) )/ch1.get(k,1) ,2)for k in set(ch1) | set(ch2)}
    changes1 =OrderedDict(sorted(changes1.items()))
    # for i,j in changes1.items():
    #     changes1.update({i: round(j,2)})
    # changes1 =dict(sorted(changes1.items()))
    # chan1 = Move.objects.filter(timestamp__contains=now_date)
    # chan2 = Move.objects.filter(timestamp__contains=yesterdate)
    # chan1 = {obj.name: obj for obj in chan1}
    # chan2 = {obj.name: obj for obj in chan2}
    # ch1 = {}
    # ch2 = {}
    # for i in chan1.values():
    #     ch1.update({i.name: i.value})
    # for i in chan2.values():
    #     ch2.update({i.name: i.value})
    # changes2 = {k: (ch1.get(k, 0) - ch2.get(k, 0)) / ch1.get(k, 0) for k in set(ch1) | set(ch2)}
    # chan1 = Windpressure.objects.filter(timestamp__contains=now_date)
    # chan2 = Windpressure.objects.filter(timestamp__contains=yesterdate)
    # chan1 = {obj.name: obj for obj in chan1}
    # chan2 = {obj.name: obj for obj in chan2}
    # ch1 = {}
    # ch2 = {}
    # for i in chan1.values():
    #     ch1.update({i.name: i.value})
    # for i in chan2.values():
    #     ch2.update({i.name: i.value})
    # changes3 = {k: (ch1.get(k, 0) - ch2.get(k, 0)) / ch1.get(k, 0) for k in set(ch1) | set(ch2)}
    # chan1 = Powerall.objects.filter(timestamp__contains=now_date)
    # chan2 = Powerall.objects.filter(timestamp__contains=yesterdate)
    # chan1 = {obj.name: obj for obj in chan1}
    # chan2 = {obj.name: obj for obj in chan2}
    # ch1 = {}
    # ch2 = {}
    # for i in chan1.values():
    #     ch1.update({i.name: i.value})
    # for i in chan2.values():
    #     ch2.update({i.name: i.value})
    # changes4 = {k: (ch1.get(k, 0) - ch2.get(k, 0)) / ch1.get(k, 0) for k in set(ch1) | set(ch2)}
    # score =numpy.zeros(50,30)
    score =0
    # for i in range(30):
    #     day_time =now_date + datetime.timedelta(days=-i)
    #     fi =Fissure.objects.filter(timestamp__contains=day_time)
    #     wi =Windpressure.objects.filter(timestamp__contains=day_time)
    #     mo =Move.objects.filter(timestamp__contains=day_time)
    #     po =Powerall.objects.filter(timestamp__contains=day_time)
    #     fi_dict ={obj.name: obj for obj in fi}
    #     wi_dict = {obj.name: obj for obj in wi}
    #     mo_dict = {obj.name: obj for obj in mo}
    #     po_dict = {obj.name: obj for obj in po}
    #     for j in fi_dict.values():
    #         # 扣分规范
    #         if j.value >70 and j.value <100:
    #             score[int(j.name),i] =-1
    #         elif j.value>100:
    #             score[int(j.name), i] = -2
    #     for j in wi_dict.values():
    #         if j.value >70 and j.value <100:
    #             score[int(j.name),i] =-1
    #         elif j.value>100:
    #             score[int(j.name), i] = -2
    #     for j in mo_dict.values():
    #         if j.value >70 and j.value <100:
    #             score[int(j.name),i] =-1
    #         elif j.value>100:
    #             score[int(j.name), i] = -2
    #     for j in po_dict.values():
    #         if j.value >70 and j.value <100:
    #             score[int(j.name),i] =-1
    #         elif j.value>100:
    #             score[int(j.name), i] = -2
    #
    #     score = 100+numpy.sum(score,axis=0)
    changes2=0
    changes3 = 0
    changes4 = 0

    return render(request, template_name='src/index.html', context={'result':result, 'changes1':changes1, 'changes2':changes2, 'changes3':changes3, 'changes4':changes4, 'score':score})
def change(request):
    ligechange = Change.objects.all()
    return render(request, template_name='change.html',context={'ligechange':ligechange})
def powerall(request):
    ligepowerall = Powerall.objects.all()
    return render(request, template_name='powerall.html',context={'ligepowerall':ligepowerall})


def move(request):
    ligemove = Move.objects.all()
    return render(request, template_name='move.html',context={'ligemove': ligemove})
def windpressure(request):
    ligewindpressure = Windpressure.objects.all()
    return render(request, template_name='windpressure.html',context={'ligewindpressure':ligewindpressure})

def fissure(request):
    ligefissure = Fissure.objects.all()
    return render(request, template_name='fissures.html',context={'ligefissure':ligefissure})


@require_GET
def search1(request):
    q = request.GET.get('q')
    ligechange = Change.objects.filter( Q(name__icontains=q) | Q(timestamp__icontains=q)).all()
    context = {'ligechange': ligechange}
    return render(request, template_name='change.html', context=context)

def search2(request):
    q = request.GET.get('q')
    ligemove = Move.objects.filter(Q(name__icontains=q) | Q(timestamp__icontains=q)).all()
    context = {'ligemove': ligemove }
    return render(request, template_name='move.html', context=context)

def search3(request):
    q = request.GET.get('q')
    ligefissure = Fissure.objects.filter(Q(name__icontains=q) | Q(timestamp__icontains=q)).all()
    context = {'ligefissure': ligefissure }
    return render(request, template_name='fissures.html', context=context)


def search4(request):
    q = request.GET.get('q')
    ligewindpressure = Windpressure.objects.filter(Q(name__icontains=q) | Q(timestamp__icontains=q)).all()
    context = {'ligewindpressure': ligewindpressure }
    return render(request, template_name='windpressure.html', context=context)
# myapp/views.py
def zhex(request):

    now_date = datetime.date.today()
    x_axis = []
    y_axis=[]
    for i in range(0,30):
        x_axis.append(now_date+datetime.timedelta(days=-i))
    for i in range(0,30):
        y_axis.append(round(random.random(),2))


    line_chart = Line()
    line_chart.add_xaxis(x_axis)
    line_chart.add_yaxis("测点应变", y_axis)
    line_chart.set_global_opts(title_opts=opts.TitleOpts(title="测点变化表"))
    chart_html = line_chart.render_embed()
    return render(request, 'src/zhex.html', {'chart_html': chart_html})


# myapp/views.py
from django.shortcuts import render
from django.http import JsonResponse
from datetime import datetime, timedelta
import calendar
from .models import Event


def calendar_view(request):
    today = datetime.today()
    year = today.year
    month = today.month

    # 获取当月所有事件
    events = Event.objects.filter(date__year=year, date__month=month)
    event_dates = {event.date.day: event for event in events}

    # 日历生成
    cal = calendar.monthcalendar(year, month)
    return render(request, 'src/calender.html', {
        'cal': cal,
        'event_dates': event_dates,
        'year': year,
        'month': month,
    })


def event_data_view(request, date):
    event = Event.objects.filter(date=date).first()
    if event:
        return JsonResponse({'date': event.date, 'data': event.data})
    else:
        return JsonResponse({'error': 'No data available for this date.'}, status=404)


from django.shortcuts import render, redirect, get_object_or_404
from .models import Event
from .forms import EventForm
from datetime import datetime

def event_detail(request, year, month, day):
    date = datetime(year, month, day)
    event = Event.objects.filter(date=date).first()
    return render(request, 'event_detail.html', {'event': event, 'date': date})

def edit_event(request, year, month, day):
    date = datetime(year, month, day)
    event, created = Event.objects.get_or_create(date=date)

    if request.method == "POST":
        form = EventForm(request.POST, instance=event)
        if form.is_valid():
            form.save()
            return redirect('event_detail', year=year, month=month, day=day)
    else:
        form = EventForm(instance=event)

    return render(request, 'edit_event.html', {'form': form, 'date': date})







